<script setup lang="ts">
import type { Coupon } from '@/types/mall'
import { formatPrice, formatTime } from '@/utils/mall'

// 当前选中的标签
const activeTab = ref('available')

// 优惠券列表
const coupons = ref<Record<string, Coupon[]>>({
  available: [],
  used: [],
  expired: [],
})

const loading = ref(false)

// 模拟优惠券数据
const mockCoupons: Coupon[] = [
  {
    id: '1',
    name: '新用户专享',
    type: 'fixed',
    value: 5000, // 50元
    minAmount: 10000, // 满100元
    validFrom: new Date().toISOString(),
    validTo: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
    totalCount: 1000,
    usedCount: 120,
    userLimit: 1,
    status: 'active',
    description: '新用户专享50元优惠券，满100元可用',
    createdAt: new Date().toISOString(),
  },
  {
    id: '2',
    name: '全场通用',
    type: 'percent',
    value: 0.95, // 95折
    minAmount: 20000, // 满200元
    maxDiscount: 10000, // 最大优惠100元
    validFrom: new Date().toISOString(),
    validTo: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),
    totalCount: 500,
    usedCount: 80,
    userLimit: 2,
    status: 'active',
    description: '全场通用95折券，满200元可用，最大优惠100元',
    createdAt: new Date().toISOString(),
  },
  {
    id: '3',
    name: '包邮券',
    type: 'shipping',
    value: 0,
    minAmount: 5000, // 满50元
    validFrom: new Date().toISOString(),
    validTo: new Date(Date.now() + 15 * 24 * 60 * 60 * 1000).toISOString(),
    totalCount: 2000,
    usedCount: 300,
    userLimit: 3,
    status: 'active',
    description: '包邮券，满50元免运费',
    createdAt: new Date().toISOString(),
  },
  {
    id: '4',
    name: '限时抢购',
    type: 'fixed',
    value: 2000, // 20元
    minAmount: 8000, // 满80元
    validFrom: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString(),
    validTo: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString(),
    totalCount: 100,
    usedCount: 100,
    userLimit: 1,
    status: 'expired',
    description: '限时抢购20元券，已过期',
    createdAt: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString(),
  },
]

// 标签页配置
const tabs = [
  { key: 'available', title: '可使用', count: 0 },
  { key: 'used', title: '已使用', count: 0 },
  { key: 'expired', title: '已过期', count: 0 },
]

// 获取优惠券列表
async function getCouponList() {
  try {
    loading.value = true
    
    // TODO: 调用API获取优惠券列表
    // const response = await api.coupon.getCouponList()
    // const allCoupons = response.data
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    const allCoupons = mockCoupons
    
    // 分类优惠券
    const now = new Date()
    coupons.value = {
      available: allCoupons.filter(coupon => {
        const validTo = new Date(coupon.validTo)
        return coupon.status === 'active' && validTo > now
      }),
      used: allCoupons.filter(coupon => coupon.status === 'used'),
      expired: allCoupons.filter(coupon => {
        const validTo = new Date(coupon.validTo)
        return coupon.status === 'expired' || validTo <= now
      }),
    }
    
    // 更新标签页计数
    tabs.forEach(tab => {
      tab.count = coupons.value[tab.key].length
    })
  } catch (error) {
    console.error('获取优惠券列表失败:', error)
    uni.showToast({ title: '获取优惠券失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

// 使用优惠券
function useCoupon(couponId: string) {
  uni.showModal({
    title: '使用优惠券',
    content: '确定要立即使用这张优惠券吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          // TODO: 调用API使用优惠券
          // await api.coupon.useCoupon(couponId)
          
          uni.showToast({ title: '已添加到购物车', icon: 'success' })
          // 重新获取列表
          getCouponList()
        } catch (error) {
          console.error('使用优惠券失败:', error)
          uni.showToast({ title: '使用失败', icon: 'none' })
        }
      }
    }
  })
}

// 格式化优惠券值
function formatCouponValue(coupon: Coupon): string {
  switch (coupon.type) {
    case 'fixed':
      return formatPrice(coupon.value)
    case 'percent':
      return `${((1 - coupon.value) * 10).toFixed(1)}折`
    case 'shipping':
      return '包邮'
    default:
      return ''
  }
}

// 格式化使用条件
function formatCouponCondition(coupon: Coupon): string {
  if (coupon.type === 'shipping') {
    return `满${formatPrice(coupon.minAmount)}免运费`
  }
  
  let condition = `满${formatPrice(coupon.minAmount)}可用`
  
  if (coupon.type === 'percent' && coupon.maxDiscount) {
    condition += `，最高优惠${formatPrice(coupon.maxDiscount)}`
  }
  
  return condition
}

// 检查优惠券是否即将过期
function isExpiringSoon(coupon: Coupon): boolean {
  const validTo = new Date(coupon.validTo)
  const now = new Date()
  const threeDaysLater = new Date(now.getTime() + 3 * 24 * 60 * 60 * 1000)
  return validTo <= threeDaysLater && validTo > now
}

// 切换标签页
function switchTab(tab: string) {
  activeTab.value = tab
}

// 页面生命周期
onMounted(() => {
  getCouponList()
})
</script>

<template>
  <view class="coupon-page">
    <!-- 标签页 -->
    <view class="tabs">
      <view
        v-for="tab in tabs"
        :key="tab.key"
        class="tab-item"
        :class="{ active: activeTab === tab.key }"
        @click="switchTab(tab.key)"
      >
        <text class="tab-title">{{ tab.title }}</text>
        <text class="tab-count">({{ tab.count }})</text>
      </view>
    </view>

    <!-- 优惠券列表 -->
    <view class="coupon-list">
      <view v-if="loading" class="loading-container">
        <wd-loading size="24px" />
        <text>加载中...</text>
      </view>

      <view v-else-if="coupons[activeTab].length === 0" class="empty-state">
        <wd-icon name="coupon" size="60px" color="#ddd" />
        <text class="empty-text">暂无优惠券</text>
      </view>

      <view v-else class="coupon-items">
        <view
          v-for="coupon in coupons[activeTab]"
          :key="coupon.id"
          class="coupon-item"
          :class="{
            expired: activeTab === 'expired',
            used: activeTab === 'used',
            expiring: isExpiringSoon(coupon)
          }"
        >
          <!-- 优惠券主体 -->
          <view class="coupon-main">
            <!-- 左侧金额 -->
            <view class="coupon-value">
              <text class="value-text">{{ formatCouponValue(coupon) }}</text>
              <text class="condition-text">{{ formatCouponCondition(coupon) }}</text>
            </view>

            <!-- 中间信息 -->
            <view class="coupon-info">
              <text class="coupon-name">{{ coupon.name }}</text>
              <text class="coupon-desc">{{ coupon.description }}</text>
              <text class="valid-time">
                有效期：{{ formatTime(coupon.validTo, 'YYYY-MM-DD') }}
              </text>
            </view>

            <!-- 右侧按钮 -->
            <view class="coupon-action">
              <wd-button
                v-if="activeTab === 'available'"
                type="primary"
                size="small"
                @click="useCoupon(coupon.id)"
              >
                立即使用
              </wd-button>
              
              <view v-else-if="activeTab === 'used'" class="status-tag used">
                已使用
              </view>
              
              <view v-else class="status-tag expired">
                已过期
              </view>
            </view>
          </view>

          <!-- 即将过期提示 -->
          <view v-if="isExpiringSoon(coupon)" class="expiring-tip">
            <wd-icon name="clock" size="12px" color="#ff4142" />
            <text>即将过期</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.coupon-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.tabs {
  display: flex;
  background: white;
  border-bottom: 1px solid #f0f0f0;

  .tab-item {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 15px 10px;
    gap: 4px;

    &.active {
      .tab-title {
        color: var(--wot-color-theme);
        font-weight: bold;
      }
    }

    .tab-title {
      font-size: 15px;
      color: #333;
    }

    .tab-count {
      font-size: 12px;
      color: #999;
    }
  }
}

.coupon-list {
  padding: 15px;

  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
    gap: 15px;
    font-size: 14px;
    color: #666;
  }

  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;

    .empty-text {
      margin-top: 15px;
      font-size: 16px;
      color: #999;
    }
  }

  .coupon-items {
    .coupon-item {
      background: white;
      border-radius: 8px;
      margin-bottom: 15px;
      overflow: hidden;
      position: relative;

      &.expired,
      &.used {
        opacity: 0.6;
      }

      &.expiring {
        border: 1px solid #ff4142;
      }

      .coupon-main {
        display: flex;
        align-items: center;
        padding: 20px;

        .coupon-value {
          width: 100px;
          text-align: center;
          margin-right: 15px;

          .value-text {
            display: block;
            font-size: 24px;
            font-weight: bold;
            color: #ff4142;
            margin-bottom: 4px;
          }

          .condition-text {
            font-size: 10px;
            color: #999;
          }
        }

        .coupon-info {
          flex: 1;
          margin-right: 15px;

          .coupon-name {
            display: block;
            font-size: 16px;
            font-weight: bold;
            color: #333;
            margin-bottom: 6px;
          }

          .coupon-desc {
            display: block;
            font-size: 12px;
            color: #666;
            margin-bottom: 4px;
          }

          .valid-time {
            font-size: 11px;
            color: #999;
          }
        }

        .coupon-action {
          .status-tag {
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            text-align: center;

            &.used {
              background: #f0f0f0;
              color: #999;
            }

            &.expired {
              background: #ffe6e6;
              color: #ff4142;
            }
          }
        }
      }

      .expiring-tip {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 4px;
        padding: 8px;
        background: #fff5f5;
        border-top: 1px solid #ffe6e6;
        font-size: 12px;
        color: #ff4142;
      }
    }
  }
}
</style>

<route lang="json">
{
  "name": "couponList",
  "style": {
    "navigationBarTitleText": "优惠券"
  }
}
</route>